import type { AxiosError, AxiosInstance } from 'axios'

export function useInterceptors(instance: AxiosInstance) {
  instance.interceptors.request.use(
    (config) => {
      if (config.data instanceof FormData) return config

      // 去除参数中的空格
      if (config.data) {
        config.data = JSON.parse(
          JSON.stringify(config.data, (_, value) => {
            if (typeof value == 'string') return value.trim()

            return value
          })
        )
      }

      return config
    },
    (error: AxiosError) => {
      return Promise.reject(error)
    }
  )

  instance.interceptors.response.use(
    (response) => {
      return response
    },
    (error: AxiosError) => {
      if (error.response?.status === 401) {
        // localStorage.clear()
        // window.location.reload()
      }

      return Promise.reject(error)
    }
  )
}
